package com.wlyy.starter.mybatis;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.wlyy.starter.mybatis.expand.InsertBatch;
import com.wlyy.starter.mybatis.expand.InsertOrUpdate;
import com.wlyy.starter.mybatis.expand.InsertOrUpdateAll;
import com.wlyy.starter.mybatis.expand.SelectByOrgId;
import com.wlyy.starter.mybatis.expand.SelectLimitOne;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.annotation.PostConstruct;
import java.util.List;

@Slf4j
@Configuration
@ConditionalOnClass(MybatisPlusAutoConfiguration.class)
@ConditionalOnProperty(value = "mybatis.plus.expand.enabled", matchIfMissing = true)
public class MybatisPlusAutoConfiguration {
    @Bean
    @Primary
    public ExpandInject sqlInjector() {
        return new ExpandInject();
    }

    public class ExpandInject extends DefaultSqlInjector {
        @Override
        public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {
            List<AbstractMethod> methodList = super.getMethodList(mapperClass, tableInfo);
            methodList.add(new InsertBatch(InsertBatch.METHOD_ID));
            methodList.add(new InsertOrUpdate(InsertOrUpdate.METHOD_ID));
            methodList.add(new InsertOrUpdateAll(InsertOrUpdateAll.METHOD_ID));
            methodList.add(new SelectByOrgId(SelectByOrgId.METHOD_ID));
            methodList.add(new SelectLimitOne(SelectLimitOne.METHOD_ID));
            return methodList;
        }

        @PostConstruct
        public void init() {
            log.debug("mybatis-plus expand method has opened");
        }
    }

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }
}
